package com.example.springsecuritydemo.service;

import com.example.springsecuritydemo.dao.CommonUserDao;
import com.example.springsecuritydemo.entities.SecurityUser;
import com.example.springsecuritydemo.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2021-06-24 下午2:20
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    private CommonUserDao commonUserDao;

    @Autowired
    public void setCommonUserDao(CommonUserDao commonUserDao) {
        this.commonUserDao = commonUserDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final Optional<User> user = commonUserDao.selectUserByLoginName(username);
        return user.map(u -> new SecurityUser(u, Arrays.asList("role")))
                .orElseThrow(() -> new UsernameNotFoundException("用户名不存在"));
    }
}
